﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using ExpertMIS.Brokers;
using System.Collections;
using IBatisNet.Common.Utilities;
using ExpertMIS.Entities;
using System.Data;
using System.Text;

namespace ExpertMIS.Service {
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class DomainQuestion: IHttpHandler {
        private int _titleLong = 30;
        private DomainBroker _domainBroker = new DomainBroker();
        private QuestionBroker _questionBroker = new QuestionBroker();
        private ADMUserBroker _userBroker = new ADMUserBroker();
        private bool _asObjectList = false;
        private Dictionary<string, string> _propFieldMapping = new Dictionary<string, string>();

        private string RefreshDomain(HttpRequest Request, string DomainOID, string filter) {
            Hashtable htKeys = new Hashtable();
            htKeys["OID"] = DomainOID;
            PagingSize pagingSize = new PagingSize();
            StringBuilder sbRet = new StringBuilder();

            int start = 0;
            if(!int.TryParse(Request["start"], out start)) {
                start = -1;
            } else if(start <= 0) {
                start = 1;
            }

            int limit = 0;
            if(!int.TryParse(Request["limit"], out limit)) {
                limit = -1;
            } else if(limit <= 0) {
                limit = 10;
            }

            if(!int.TryParse(ExpertMIS.Codes.Utility.GetEnvironmentValue("domainquestion.length"), out _titleLong)) {
                _titleLong = 30;
            }

            //sbRet.Append("<tr class='result-head'><td class='col-title'>标题</td><td class='col-poster'>提问人</td><td class='col-date'>时间</td><td class='col-status'>状态</td></tr>");            
            sbRet.Append("<tr class='result-head'><td class='col-title'>标题</td><td class='col-status'>状态</td><td class='col-answer'>答案</td><td class='col-date'>时间</td></tr>");

            if(start == -1 || limit == -1) {
                IList<QuestionEntity> questions = null;

                _asObjectList = true;
                if(string.IsNullOrEmpty(filter) || "all".Equals(filter)) {
                    questions = _questionBroker.GetDomainLastQuestion(DomainOID, 10);
                } else if("resolved".Equals(filter)) {
                    questions = _questionBroker.GetDomainResolvedQuestionsByStatus(DomainOID, 10);
                } else if("unsolved".Equals(filter)) {
                    questions = _questionBroker.GetDomainUnsolvedQuestionsByStatus(DomainOID, 10);
                }

                foreach(QuestionEntity question in questions) {
                    sbRet.Append("<tr>");

                    sbRet.Append(string.Format("<td><a href='QuestionForm.aspx?oid={1}' target='_blank'>{0}</a></td>", ExpertMIS.Codes.Utility.CutLongText(question.Title, _titleLong), question.OID));

                    //ADMUserEntity user = _userBroker.GetEntityByOID(question.UserOID);
                    //if(user != null) {
                    //    sbRet.Append(string.Format("<td>{0}</td>", user.Name));
                    //} else {
                    //    sbRet.Append("<td></td>");
                    //}

                    sbRet.Append(string.Format("<td>{0}</td>", QuestionBroker.TranslateQuestionStatus(question.Status)));
                    sbRet.Append(string.Format("<td>{0}</td>", QuestionBroker.TranslateAnswerStatus(question.Status)));
                    sbRet.Append(string.Format("<td>{0:yy-MM-dd}</td>", question.UpdateDate));
                    sbRet.Append("</tr>");
                }
            } else {
                DataTable questions = null;

                _asObjectList = false;
                pagingSize.Start = start;
                pagingSize.Limit = limit;
                pagingSize.SortExpression = "F_UPDATEDATE DESC, F_CREATEDATE DESC";
                pagingSize.SearchKey = "";

                if("".Equals(filter) || "all".Equals(filter)) {
                    questions = _questionBroker.GetDomainAllPassedQuestions(DomainOID, pagingSize);
                } else if("resolved".Equals(filter)) {
                    questions = _questionBroker.GetDomainResolvedQuestionsByStatus(DomainOID, pagingSize);
                } else if("unsolved".Equals(filter)) {
                    questions = _questionBroker.GetDomainUnsolvedQuestionsByStatus(DomainOID, pagingSize);
                }

                foreach(DataRowView row in questions.DefaultView) {
                    sbRet.Append("<tr>");

                    sbRet.Append(string.Format("<td><a href='QuestionForm.aspx?oid={1}' target='_blank'>{0}</a></td>", ExpertMIS.Codes.Utility.CutLongText(row["F_Title"], _titleLong), row["F_OID"]));

                    //ADMUserEntity user = _userBroker.GetEntityByOID(row["F_UserOID"].ToString());
                    //if(user != null) {
                    //    sbRet.Append(string.Format("<td>{0}</td>", user.Name));
                    //} else {
                    //    sbRet.Append("<td></td>");
                    //}


                    sbRet.Append(string.Format("<td>{0}</td>", QuestionBroker.TranslateQuestionStatus((QuestionStatus)row["F_Status"])));
                    sbRet.Append(string.Format("<td>{0}</td>", QuestionBroker.TranslateAnswerStatus((QuestionStatus)row["F_Status"])));

                    sbRet.Append(string.Format("<td>{0:yy-MM-dd}</td>", row["F_UpdateDate"]));
                    sbRet.Append("</tr>");
                }
            }

            return string.Format("<table cellpadding='0' cellspacing='0' id='result' pageno='{1}' pagecount='{2}' recordcount='{3}'>{0}</table>", sbRet.ToString(), pagingSize.Start, pagingSize.Total == 0 ? pagingSize.Total : (int)System.Math.Ceiling((double)pagingSize.Total / pagingSize.Limit), pagingSize.Total);
        }

        protected string GetMappingField(string name) {
            if(_asObjectList) {
                return name;
            } else {
                if(_propFieldMapping.ContainsKey(name)) {
                    return _propFieldMapping[name];
                }
                return name;
            }
        }

        public void ProcessRequest(HttpContext context) {
            context.Response.ContentType = "text/html";
            context.Response.Write(RefreshDomain(context.Request, context.Request["oid"], context.Request["filter"]));
        }

        public bool IsReusable {
            get {
                return false;
            }
        }
    }
}
